/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import request from 'umi-request';
import {getToken} from "@/utils/token.ts";


// 封装get请求
export const get = (url:string, params:object) => {
    return request(url, {
        method: 'GET',
        params: params,
    });
};

// 封装post请求
export const post = (url:string, data:object) => {
    return request(url, {
        method: 'POST',
        data: data,
    });
};

// request拦截器, 改变url 或 options.
request.interceptors.request.use(async (url, options) => {
    let token = getToken();
    if (token) {
        const headers = {
            Authorization: 'Bearer ' + token,
            token: token
        };
        Object.assign(headers, options.headers);
        return {
            url: url,
            options: { ...options, headers: headers },
        };
    }
    return {
        url: url,
        options: { ...options },
    };
});

// 使用封装后的请求方法
// get('https://api.example.com/data', { id: 123 })
//     .then(response => console.log(response))
//     .catch(error => console.error(error));

// post('https://api.example.com/data', { key: 'value' })
//     .then(response => console.log(response))
//     .catch(error => console.error(error));